package com.th.cash.th2.product

import android.content.Intent
import android.net.Uri
import androidx.activity.viewModels
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.lxj.xpopup.XPopup
import com.th.basemodel.base.BaseVB2Activity2
import com.th.basemodel.base.BaseViewModel
import com.th.resmodel.databinding.ActivityProductBinding
import com.th.cash.storage.LocalSetting
import com.th.cash.util.ActivityRouter
import kotlinx.coroutines.launch

class ProductActivity : BaseVB2Activity2<ActivityProductBinding>() {

    var pid = ""
    var oid = ""
    private var detail = ""

    private var fragment: VerifyBaseFragment<*>? = null

    companion object {
        var URI = "uri"
    }

    private val mViewModel by viewModels<ProductVm>()

    override fun getVm(): BaseViewModel {
        return mViewModel
    }

    override fun setWindowPadding() {
        ViewCompat.setOnApplyWindowInsetsListener(mBinding.main) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            insets
        }
    }

    override fun getDataFromIntent(intent: Intent) {
        parseUri(intent.getStringExtra(URI) ?: "")
    }

    private fun parseUri(uriStr: String) {
        try {
            val uri = Uri.parse(uriStr)
            pid = uri.getQueryParameter("KiOAYsXOverrelianceWWpzcfA") ?: ""
            detail = uri.getQueryParameter("detail") ?: ""
            oid = uri.getQueryParameter("oid") ?: ""
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun init() {
        initTitle()
        loadFragment(detail)
    }

    private fun initTitle() {
    }

    fun loadFragment(path: String) {
        detail = path
        fragment = when (path) {
            "info" -> DetailFragment.newInstance()
            "REUXADXWPOEEPPI" -> BasicFragment.newInstance()
            "TQAPPIJHQXNDYYI" -> ContactFragment.newInstance()
            "CUTIOOETBPDDIQR" -> BankFragment.newInstance()
            "VILYSZDDEYZJDEF" -> IdFragment.newInstance()
            else -> null
        }

        fragment?.let {
            supportFragmentManager.beginTransaction()
                .replace(mBinding.productScreen.id, it)
                .commitAllowingStateLoss()
        }
    }

    fun getOrderUrl() {
        mViewModel.intentChannel.trySend(
            ProductIntent.GetOrderUrl(
                OrderUrlRequest(
                    oid,
                    "houijhyus"
                )
            )
        )
    }

    override fun observeViewModel() {
        lifecycleScope.launch {
            mViewModel.uiState.collect {
                when (it) {
                    is ProductState.Idle -> {

                    }

                    is ProductState.ShowDetail -> {
                        ActivityRouter.next(this@ProductActivity, it.data)
                        this@ProductActivity.finish()
                    }

                    else -> {}
                }
            }
        }
    }

    private fun back() {
        if (detail == "info") {
            finish()
        } else {
            if (LocalSetting.userAdult) {
                loadFragment("info")
            } else {
                finish()
            }
        }
    }

    fun showRetentionPopup(type: Int) {
        if (type == 0) {
            back()
            return
        }
        XPopup.Builder(this)
            .asCustom(
                UserRetentionPopup(
                    this,
                    type
                ).run {
                    clickListener = { sure ->
                        if (sure) {
                            back()
                        }
                    }
                    this
                })
            .show()
    }

    override fun onBackPressed() {
//        super.onBackPressed()

        showRetentionPopup(fragment?.type ?: 0)
    }
}